/*
 * Copyright (c) 2016-present The ZLMediaKit project authors. All Rights Reserved.
 *
 * This file is part of ZLMediaKit(https://github.com/ZLMediaKit/ZLMediaKit).
 *
 * Use of this source code is governed by MIT-like license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
 */

 #include <signal.h>
 #include <string.h>
 #include <stdio.h>
 #include "unistd.h"
 #include "mk_mediakit.h"
 #include "RtspServer.h"

 static int trackflag = 0;
 // 按照json转义规则转义webrtc answer sdp  [AUTO-TRANSLATED:b9373d68]
 // Escape the webrtc answer sdp according to json escape rules
 static char* escape_string(const char* ptr) {
     char* escaped = malloc(2 * strlen(ptr));
     char* ptr_escaped = escaped;
     while (1) {
         switch (*ptr) {
         case '\r': {
             *(ptr_escaped++) = '\\';
             *(ptr_escaped++) = 'r';
             break;
         }
         case '\n': {
             *(ptr_escaped++) = '\\';
             *(ptr_escaped++) = 'n';
             break;
         }
         case '\t': {
             *(ptr_escaped++) = '\\';
             *(ptr_escaped++) = 't';
             break;
         }
 
         default: {
             *(ptr_escaped++) = *ptr;
             if (!*ptr) {
                 return escaped;
             }
             break;
         }
         }
         ++ptr;
     }
 }
 
 static void on_mk_webrtc_get_answer_sdp_func(void* user_data, const char* answer, const char* err) {
     const char* response_header[] = { "Content-Type", "application/json", "Access-Control-Allow-Origin", "*" , NULL };
     if (answer) {
         answer = escape_string(answer);
     }
     size_t len = answer ? 2 * strlen(answer) : 1024;
     char* response_content = (char*)malloc(len);
 
     if (answer) {
         snprintf(response_content, len,
             "{"
             "\"sdp\":\"%s\","
             "\"type\":\"answer\","
             "\"code\":0"
             "}",
             answer);
     }
     else {
         snprintf(response_content, len,
             "{"
             "\"msg\":\"%s\","
             "\"code\":-1"
             "}",
             err);
     }
 
     mk_http_response_invoker_do_string(user_data, 200, response_header, response_content);
     mk_http_response_invoker_clone_release(user_data);
     free(response_content);
     if (answer) {
         free((void*)answer);
     }
 }
 
static char rsq[256] = "{\"code\":0,\"msg\":\"ok\",\"roi_points\":[{\"x\":0.25,\"y\":0.25},{\"x\":0.75,\"y\":0.25},{\"x\":0.75,\"y\":0.75},{\"x\":0.25,\"y\":0.75}]}";
 void API_CALL on_mk_http_request(const mk_parser parser,
     const mk_http_response_invoker invoker,
     int* consumed,
     const mk_sock_info sender) {
 
     const char* url = mk_parser_get_url(parser);
     *consumed = 1;
 
     // printf("url=%s \n",url);
     if (strcmp(url, "/capture") == 0) {
         // 处理拍照请求
         const char* response_headers[] = { "Content-Type", "application/json", "Access-Control-Allow-Origin", "*", NULL };
         const char* response = "{\"status\":\"拍照正常\"}";
         mk_http_response_invoker_do_string(invoker, 200, response_headers, response);
         return;
     }
     else if (strcmp(url, "/riocfg") == 0)
     {
         // get {"code":0,"msg":"ok","roi_points":[{"x":0.25,"y":0.25},{"x":0.75,"y":0.25},{"x":0.75,"y":0.75},{"x":0.25,"y":0.75}]}
         // post {"roi_points":[{"x":0.25,"y":0.25},{"x":0.75,"y":0.25},{"x":0.75,"y":0.75},{"x":0.25,"y":0.75}]}  return "{"code":0,"msg":"ok"}"

         const char *response_headers[] = {"Content-Type", "application/json", "Access-Control-Allow-Origin", "*", NULL};
         const char *method = mk_parser_get_method(parser);
         const char *content = mk_parser_get_content(parser, NULL);
         if (0 == strcmp(method, "POST") || 0 == strcmp(method, "post"))
         {
             memset(rsq, 0x00, sizeof(rsq));
             const *header = "{\"code\":0,\"msg\":\"ok\",";
             strcpy(rsq, header);
             strcpy(rsq + strlen(header), content + 1);

             const char *response = "{\"code\":0,\"msg\":\"ok\"}";
             mk_http_response_invoker_do_string(invoker, 200, response_headers, response);
             return;
         }
         mk_http_response_invoker_do_string(invoker, 200, response_headers, rsq);
         return;
     }
     if (strcmp(url, "/index/api/webrtc") == 0) {
         // 拦截api: /index/api/webrtc  [AUTO-TRANSLATED:1db21d1c]
         // Intercept api: /index/api/webrtc
         char rtc_url[1024];
         snprintf(rtc_url, sizeof(rtc_url), "rtc://%s/%s/%s?%s", mk_parser_get_header(parser, "Host"),
             mk_parser_get_url_param(parser, "app"), mk_parser_get_url_param(parser, "stream"),
             mk_parser_get_url_params(parser));
         mk_webrtc_get_answer_sdp(mk_http_response_invoker_clone(invoker), on_mk_webrtc_get_answer_sdp_func,
             mk_parser_get_url_param(parser, "type"), mk_parser_get_content(parser, NULL), rtc_url);
     }
     else {
         *consumed = 0;
         return;
     }
 }
 
 mk_media RtspServerInit(const char* stream_name) {
     
     char* ini_path = mk_util_get_exe_dir("config.ini");
     mk_config config = {
             .ini = ini_path,
             .ini_is_path = 1,
             .log_level = 0,
             .log_mask = LOG_CONSOLE,
             .log_file_path = NULL,
             .log_file_days = 0,
             .ssl = NULL,
             .ssl_is_path = 1,
             .ssl_pwd = NULL,
             .thread_num = 0
     };
     mk_env_init(&config);
     mk_free(ini_path);
     mk_http_server_start(80, 0);
     mk_rtsp_server_start(554, 0);
     mk_rtmp_server_start(1935, 0);
     mk_rtc_server_start(atoi(mk_get_option("rtc.port")));
     mk_events events = {
             .on_mk_media_changed = NULL,
             .on_mk_media_publish = NULL,
             .on_mk_media_play = NULL,
             .on_mk_media_not_found = NULL,
             .on_mk_media_no_reader = NULL,
             .on_mk_http_request = on_mk_http_request,
             .on_mk_http_access = NULL,
             .on_mk_http_before_access = NULL,
             .on_mk_rtsp_get_realm = NULL,
             .on_mk_rtsp_auth = NULL,
             .on_mk_record_mp4 = NULL,
             .on_mk_shell_login = NULL,
             .on_mk_flow_report = NULL
     };
     mk_events_listen(&events);
     mk_media media = mk_media_create("__defaultVhost__", "live", stream_name, 0, 0, 0);
     return media;
 }
 void RtspServerunInit(mk_media media)
 {
     mk_media_release(media);
     mk_stop_all_server();
     trackflag = 0;
 }
 
//  void RtspPutframe(mk_media media, const char* data, int size) {
//      if (trackflag == 0)
//      {
//          // h264的codec  [AUTO-TRANSLATED:940c6a32]
//          // h264 codec
//          codec_args v_args = { 0 };
//          // mk_media_init_video(media, 0, 0, 0, 0, 2 * 104 * 1024);
//          mk_track v_track = mk_track_create(MKCodecH264, &v_args);
//          mk_media_init_track(media, v_track);
//          mk_media_init_complete(media);
//          mk_track_unref(v_track);
//          trackflag = 1;
//      }
//      uint64_t dts = mk_util_get_current_millisecond();
//      mk_frame frame = mk_frame_create(MKCodecH264, dts, dts, data, size, NULL, NULL);
//      mk_media_input_frame(media, frame);
//      mk_frame_unref(frame);
//  }
 